package com.xsm.activitygroup;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.umeng.analytics.MobclickAgent;
import com.xsm.activitygroup.R;
import com.xsm.adapter.BooksAdapter;
import com.xsm.adapter.ViewPagerAdapter;
import com.xsm.internet.PostMessage;
import com.xsm.object.BookObject;

import android.R.integer;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.PagerTitleStrip;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.text.format.DateUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AbsListView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
public class Trade extends Activity{
	private ViewPager viewPager;
    private View view1, view2;
    private ViewPagerAdapter adapter;
    private List<View> views;
    private TextView title1,title2;
    ImageView imageView;
    private int offset;
    private int currIndex = 0;// 当前页卡编号  
    private PullToRefreshListView selllist,hadselllist;
	BooksAdapter sellAdapter,hadsellAdapter;
	LinearLayout checkLogins,checkLoginh;
	RelativeLayout loadlLayouts,loadlLayouth;
	LinearLayout pullLayouts,pullLayouth;
	ArrayList<BookObject> sellbooks=new ArrayList<BookObject>();
	ArrayList<BookObject> hadsellbooks=new ArrayList<BookObject>();
	int sellpage=0,hadsellpage=0;
	Context context;
	Myhandler handler;
	Thread loadsell,loadhadsell;
	String userid="";
	int sellsate=0,hadsellstate=0;
	private boolean scrollFlag = false;// 标记是否滑动
	private int selllastVisib,hadselllastVisib;// 标记上次滑动位置
	
	
	
    protected void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	requestWindowFeature(Window.FEATURE_NO_TITLE);
	setContentView(R.layout.trade);
	context=this;
	handler=new Myhandler();
	SharedPreferences sharedPreferences=getSharedPreferences("XSM", 0);
	userid=sharedPreferences.getString("User", "");
	initView();
}
    

private void initView(){
	  viewPager = (ViewPager) findViewById(R.id.viewpager); 
	  title1=(TextView)findViewById(R.id.title1);
	  title2=(TextView)findViewById(R.id.title2);
	  imageView= (ImageView) findViewById(R.id.cursor); 
	  DisplayMetrics dm = new DisplayMetrics();  
      getWindowManager().getDefaultDisplay().getMetrics(dm);  
      int screenW = dm.widthPixels;// 获取分辨率宽度  
      Matrix matrix = new Matrix(); 
      offset=screenW/2;
      matrix.postTranslate(offset, 0);  
      imageView.setImageMatrix(matrix);// 设置动画初始位置  
	  views=new ArrayList();
      LayoutInflater lf = getLayoutInflater().from(this);  
      view1 = lf.inflate(R.layout.goodslist, null);  
      view2 = lf.inflate(R.layout.goodslist, null);  
      views.add(view1);
      views.add(view2);
      
      title1.setText("出售中的商品");
      title2.setText("已出售的商品");
      
      title1.setOnClickListener(new MYbuttonListener(0));
      title2.setOnClickListener(new MYbuttonListener(1));
      
      adapter=new ViewPagerAdapter(views);
      viewPager.setAdapter(adapter);  
      viewPager.setCurrentItem(0);  
      viewPager.setOnPageChangeListener(new MyOnPageChangeListener());  
      initGoods();
}

protected void onResume() {
		MobclickAgent.onResume(this);
	super.onResume();
}

protected void onPause() {
	MobclickAgent.onResume(this);
	super.onPause();
}

private void initGoods(){
    checkLogins=(LinearLayout)view1.findViewById(R.id.checkLogin);
    checkLoginh=(LinearLayout)view2.findViewById(R.id.checkLogin);
    
    loadlLayouts=(RelativeLayout)view1.findViewById(R.id.loadlayout);
    loadlLayouth=(RelativeLayout)view2.findViewById(R.id.loadlayout);
   
   pullLayouts=(LinearLayout)view1.findViewById(R.id.pullview);
   pullLayouth=(LinearLayout)view2.findViewById(R.id.pullview);
   
	
	
	selllist=(PullToRefreshListView)view1.findViewById(R.id.goodslist);
	sellAdapter=new BooksAdapter(context, sellbooks);
	selllist.setAdapter(sellAdapter);
	selllist.setOnRefreshListener(new OnRefreshListener<ListView>() {
	public void onRefresh(PullToRefreshBase<ListView> refreshView) {
		String label = DateUtils.formatDateTime(getApplicationContext(), System.currentTimeMillis(),
				DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_ALL);
		refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);
           loadsell=new LoadThread(0);
           loadsell.start();
		}
	});
	
	selllist.setOnItemClickListener(new OnItemClickListener() {
		public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
	  Intent intent=new Intent();
	 intent.putExtra("ms",sellbooks.get(arg2-1));
	 intent.putExtra("index",arg2-1);
	 intent.putExtra("type","sell");
	 intent.setClass(context, BookMessage.class);
	startActivityForResult(intent,2);
		}
	});
	
	
	
	selllist.setOnScrollListener(new OnScrollListener() {
		public void onScrollStateChanged(AbsListView view, int scrollState) {
			if (scrollState == OnScrollListener.SCROLL_STATE_TOUCH_SCROLL) {
				scrollFlag = true;
				} else {
				scrollFlag = false;
				}
		}
		public void onScroll(AbsListView view, int firstVisibleItem,
				int visibleItemCount, int totalItemCount) {
			if (scrollFlag) {
				if (firstVisibleItem > selllastVisib) {
					sellsate=1;
					//上滑
				}
				if (firstVisibleItem < selllastVisib) {
					sellsate=0;
					//下滑
				}
				if (firstVisibleItem == selllastVisib) {
				return;
				}
				selllastVisib = firstVisibleItem;
				}
		}
	});
	
	
	
	
	
	hadselllist=(PullToRefreshListView)view2.findViewById(R.id.goodslist);
	hadsellAdapter=new BooksAdapter(context, hadsellbooks);
	hadselllist.setAdapter(hadsellAdapter);
	hadselllist.setOnRefreshListener(new OnRefreshListener<ListView>() {
	public void onRefresh(PullToRefreshBase<ListView> refreshView) {
		String label = DateUtils.formatDateTime(getApplicationContext(), System.currentTimeMillis(),
				DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_ALL);
		refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);
           loadhadsell=new LoadThread(1);
           loadhadsell.start();
		}
	});
	
	hadselllist.setOnItemClickListener(new OnItemClickListener() {
		public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
	  Intent intent=new Intent();
	 intent.putExtra("ms",hadsellbooks.get(arg2-1));
	 intent.putExtra("index",arg2-1);
	 intent.putExtra("type","hadsell");
	 intent.setClass(context, BookMessage.class);
	startActivityForResult(intent,2);
		}
	});
	
	
	
	hadselllist.setOnScrollListener(new OnScrollListener() {
		public void onScrollStateChanged(AbsListView view, int scrollState) {
			if (scrollState == OnScrollListener.SCROLL_STATE_TOUCH_SCROLL) {
				scrollFlag = true;
				} else {
				scrollFlag = false;
				}
		}
		public void onScroll(AbsListView view, int firstVisibleItem,
				int visibleItemCount, int totalItemCount) {
			if (scrollFlag) {
				if (firstVisibleItem > hadselllastVisib) {
					hadsellstate=1;
					//上滑
				}
				if (firstVisibleItem < hadselllastVisib) {
					hadsellstate=0;
					//下滑
				}
				if (firstVisibleItem == hadselllastVisib) {
				return;
				}
				hadsellstate = firstVisibleItem;
				}
		}
	});
	
	
	
	if(userid.equals("")){
		selllist.setVisibility(View.GONE);
		hadselllist.setVisibility(View.GONE);
		checkLogins.setVisibility(View.VISIBLE);
		checkLoginh.setVisibility(View.VISIBLE);
		Button bts=(Button)checkLogins.findViewById(R.id.login);
		Button bth=(Button)checkLoginh.findViewById(R.id.login);
		bts.setOnClickListener(new OnClickListener() {
			public void onClick(View arg0) {
       startActivity(new Intent(context,Login.class));				
		finish();
			}
		});
		bth.setOnClickListener(new OnClickListener() {
			public void onClick(View arg0) {
       startActivity(new Intent(context,Login.class));				
		finish();
			}
		});
		pullLayouth.setVisibility(View.GONE);
		pullLayouts.setVisibility(View.GONE);
		
	}else {
		pullLayouth.setVisibility(View.GONE);
		selllist.setVisibility(View.GONE);
		loadlLayouts.setVisibility(View.VISIBLE);

		
		pullLayouts.setVisibility(View.GONE);
		hadselllist.setVisibility(View.GONE);
		loadlLayouth.setVisibility(View.VISIBLE);

	}
}


class MYbuttonListener implements OnClickListener{
	int index;
public MYbuttonListener(int i){
	index=i;
}
	public void onClick(View v) {
		viewPager.setCurrentItem(index);
	}
}

 class MyOnPageChangeListener implements OnPageChangeListener{
	public void onPageScrollStateChanged(int arg0) {
	}
	public void onPageScrolled(int arg0, float arg1, int arg2) {
	}
	public void onPageSelected(int arg0) {
		 Animation animation = new TranslateAnimation(offset*currIndex, offset*arg0, 0, 0);//显然这个比较简洁，只有一行代码。  
         currIndex = arg0;  
         animation.setFillAfter(true);// True:图片停在动画结束位置  
         animation.setDuration(300);  
         imageView.startAnimation(animation);  
         new LoadThread(currIndex).start();
	}  
 }
 
 class Myhandler extends Handler{
	public void handleMessage(Message msg) {
		if(msg.what==0){
		if(sellbooks.size()<5)
		selllist.setMode(Mode.PULL_DOWN_TO_REFRESH);
				else {
		selllist.setMode(Mode.BOTH);
		}
			
		sellAdapter.notifyDataSetChanged();
		selllist.onRefreshComplete();
		if(loadlLayouts.VISIBLE==View.VISIBLE)
		loadlLayouts.setVisibility(View.GONE);
		selllist.setVisibility(View.VISIBLE);
		if(sellbooks.size()>0)
			pullLayouts.setVisibility(View.GONE);
		else {
			if(!userid.equals(""))
			pullLayouts.setVisibility(View.VISIBLE);	
		}
		
		}else if(msg.what==1){
			if(hadsellbooks.size()<5)
				hadselllist.setMode(Mode.PULL_DOWN_TO_REFRESH);
				else {
				hadselllist.setMode(Mode.BOTH);
				}
			hadsellAdapter.notifyDataSetChanged();
			hadselllist.onRefreshComplete();
			if(loadlLayouth.VISIBLE==View.VISIBLE)
			loadlLayouth.setVisibility(View.GONE);
			hadselllist.setVisibility(View.VISIBLE);
			if(hadsellbooks.size()>0)
			pullLayouth.setVisibility(View.GONE);
			else {
				if(!userid.equals(""))
				pullLayouth.setVisibility(View.VISIBLE);	
			}	
		}
	}
 }
 
 public void Back(View view){
	 finish();
 }
 
 
 
 class LoadThread extends Thread{
	 int index;
	public LoadThread(int index){
		this.index=index;
	}

  public void run() {
	  String type="";
	  int page=0;

	  if(hadsellstate==0){
		  hadsellpage=0;
	  }else {
		  hadsellpage=hadsellbooks.size();
	  }
	  
	  
	  if(sellsate==0){
		  sellpage=0;
	  }else {
		sellpage=sellbooks.size();
	  }
	  
	  
	  
	  
	  if(index==0){
		  type="getOnline";
		page=sellpage;  
	  }
	  else if(index==1){
		  type="getOutgoods";
	      page=hadsellpage;
	  }
	  
		List params=new ArrayList();
		params.add(new BasicNameValuePair("ASK",type));
		params.add(new BasicNameValuePair("userid",userid));
		params.add(new BasicNameValuePair("page",page+""));
		
		PostMessage postMessage=new PostMessage(params);
		String result=postMessage.getResult();
		JSONArray array = null;
		try {
			 array=new JSONArray(result);
			 if(array.length()>0){
				 if(type.equals("getOnline")&&sellsate==0)
					 sellbooks.clear();
				 else if(type.equals("getOutgoods")&&hadsellstate==0){
					hadsellbooks.clear();
				}
			 }
			JSONObject jobject=new JSONObject();
			for(int i=0;i<array.length();i++){
				jobject=array.optJSONObject(i);
				
				String bookname=jobject.getString("bookname");
				String releaseType=jobject.getString("buytype");
				String time=jobject.getString("time");
				String price=jobject.getString("price");
				String bookType=jobject.getString("booktype");
				String oner=jobject.getString("username");
				String phone=jobject.getString("phone");
				String message=jobject.getString("explain");
				String school=jobject.getString("school");
				String press=jobject.getString("press");
				String goodsid=jobject.getString("goodsid");
				String author=jobject.getString("author");
				String uid=jobject.getString("userid");
				String gparentid=jobject.getString("gparentid");
				String realprice=jobject.getString("realprice");
				String path=jobject.getString("path");
				BookObject object=new BookObject();
				object.setBookName(bookname);
				object.setReleaseType(releaseType);
				object.setTime(time.substring(0,10));
				object.setPrice(price);
				object.setBookType(bookType);
				object.setOner(oner);
				object.setPhone(phone);
				object.setMessage(message);
				object.setPlace(school);
				object.setPress(press);
				object.setGoodsid(goodsid);
				object.setUserid(uid);
				object.setGparentid(gparentid);
				object.setAuthor(author);
				object.setRealprice(realprice);
				object.setPath(path);
				 if(type.equals("getOnline"))
					 sellbooks.add(object);
				 else {
					hadsellbooks.add(object);
				}
					
			}
		} catch (Exception e) {
			Log.d("my", e+"");
		}
		
		Message msg=handler.obtainMessage();
		msg.what=index;
		handler.sendMessage(msg);
		
	super.run();
   }
 }

}
